package com.shuigu.config;

import com.shuigu.anno.ServiceModule;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Service工厂
 *
 * @author ByteFun
 */

public class ServiceFactory<T>{

    private final ApplicationContext applicationContext;
    private final Class<T> serviceClass;

    private final Map<Integer, T> serviceOfType = new HashMap<>();

    public ServiceFactory(ApplicationContext applicationContext,Class<T> serviceClass) {
        this.applicationContext = applicationContext;
        this.serviceClass = serviceClass;
        Map<String, T> beansOfType = applicationContext.getBeansOfType(serviceClass);
        for (Map.Entry<String, T> entry : beansOfType.entrySet()) {
            T value = entry.getValue();
            //根据类型标识获取服务实例
            ServiceModule annotation = AnnotationUtils.findAnnotation(value.getClass(), ServiceModule.class);
            if (annotation != null) {
                this.serviceOfType.put(annotation.businessType(), value);
            }
        }
    }

    /**
     * 根据 type 获取服务实例
     *
     * @param type 服务类型标识
     * @return 返回对应类型的服务实例，如果未找到则返回 @Primary 标识的默认服务
     */
    public T getService(Integer type) {
        return this.serviceOfType.getOrDefault(type,applicationContext.getBean(serviceClass));
    }
}